using UnityEngine;
using MoonSharp.Interpreter;
using NaughtyAttributes;
using Game.Networking;
using Game.Networking.Utils;

namespace Game {
	public class TestScriptRunner : MonoBehaviour {
		[TextArea]
		public string ScriptText;
		ShipAPI _api;

		Script _shipScript;

		GlobalLuaData _globalData = new GlobalLuaData();

		private void Start() {
			if ( !NetworkOptions.StartServer ) {
				return;
			}
			LuaCustomConverters.RegisterAll();
			_api = GetComponent<ShipAPI>();
			_shipScript = new Script();
			UserData.RegisterType<ShipAPI>();
			UserData.RegisterType<GlobalLuaData>();
			var shipApi = UserData.Create(_api);
			var global = UserData.Create(_globalData);
			_shipScript.Globals.Set("ship", shipApi);
			_shipScript.Globals.Set("globals", global);
			_shipScript.DoString(ScriptText);
		}

		private void Update() {
			if ( GameManager.Instance.IsServer ) {
				_shipScript?.Call(_shipScript.Globals["update"]);
			}			
		}
	}

	public class GlobalLuaData {
		public double Time => ServerGameManager.Time;
	}
}
